package com.coolweather.android.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

import com.coolweather.android.MainActivity;
import com.coolweather.android.R;
import com.coolweather.android.gson.Weather;
import com.coolweather.android.gson.WeatherInfo;

public class MyService extends Service {
    //前台通知的id
    private static final int NOTIFICATION_ID = 1000;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //服务开始运行时调用


    //服务开始运行的时候调用
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        WeatherInfo weather = (WeatherInfo) intent.getSerializableExtra("weather");
        Notification notification = createForegroundNotification(weather);
        //以前台服务的方式唤醒通知
        startForeground(NOTIFICATION_ID,notification);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
    //创建notification
    private Notification createForegroundNotification(WeatherInfo weather) {
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        // 唯一的通知通道的id.
        String notificationChannelId = "notification_channel_id_01";
        //Android8.0以上的系统，需要新建消息通道
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelName = "前台通道服务";     //设置通道名字
            //设置通道的优先级，1000最高，依次递减
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
            notificationChannel.setDescription("一个前台通道");
            //创建通道
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(notificationChannel);
            }
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this,notificationChannelId);
        //设置通知的小图标
        builder.setSmallIcon(R.drawable.weather);
        //设置通知的标题
        builder.setContentTitle("今日温度：" + weather.getTempertate() + "℃");
        //设置通知的正文
        builder.setContentText(weather.getSuggest());
        //设置通知显示的时间
        builder.setWhen(System.currentTimeMillis());
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        //设置风格
        builder.setStyle(new NotificationCompat.BigTextStyle());
        return builder.build();
    }
}
